import threading

from util import popup_window
from util.sqlite_db import *
from PyQt5.QtWidgets import QTableWidget, QHeaderView, QFileDialog, QTableWidgetItem
import pandas as pd
from util.api_wapper import kuai_api, yemai_api, YeMaiAPI, yuan_api
from PyQt5 import QtCore, QtGui, QtWidgets, Qt


class clickFun():
    def __init__(self):
        super().__init__()

        self.tab2_log_list = []
        self.log_list = []
        self.success_log_list = []
        self.account_model = QtGui.QStandardItemModel(1, 7)  # 存储任意结构数据
        self.account_checks = []
        self.yuyue_model = QtGui.QStandardItemModel(1, 8)
        # self.timer_jiankong = QtCore.QTimer()
        # self.timer_jiankong2 = QtCore.QTimer()
        # self.timer_jiankong3 = QtCore.QTimer()
        # self.timer_jiankong4 = QtCore.QTimer()
        # self.timer_jiankong5 = QtCore.QTimer()
        # self.timer_logger = QtCore.QTimer()
        # self.timer_exec_yuan = QtCore.QTimer()
        #
        # self.jiankong_list_num = 3
        # self.jiankong_list = []
        # self.jiankong_list2 = []
        # self.jiankong_list3 = []
        # self.jiankong_list4 = []
        # self.jiankong_list5 = []
        # self.jiankong_cishu = 0
        # self.jiankong_cishu2 = 0
        # self.jiankong_cishu3 = 0
        # self.jiankong_cishu4 = 0
        # self.jiankong_cishu5 = 0

        self.log_model = Qt.QStringListModel()

        self.use_proxy = False
        self.proxy_order_id = None
        self.proxy_api_key = None
        self.yuyue_shaixuan = False
        # self.qianggou_cishu = 1000
        # self.qianggou_jiange = 500
        self.p = None

    def account_import(self):
        current_path = os.getcwd()
        filename = QFileDialog.getOpenFileName(self.groupBox_7, 'Open file',
                                               current_path,
                                               "Excel Files (*.xlsx)")

        if filename[0] != '':
            self.account_file = filename[0]
            df = pd.read_excel(self.account_file)  # 读取数据文件
            height, width = df.shape
            xf = 0
            while (xf < height):
                userid = df.iloc[xf, 0]
                mobile = df.iloc[xf, 1]
                access_token = df.iloc[xf, 2]
                userinfo = get_userlogin_mobile(mobile)
                if userinfo:
                    print("已录入")
                else:
                    create_user_login_success(mobile, access_token, userid, "是", 0)
                xf += 1
            self.user_list('YES')
            pass

    def account_export(self):
        current_path = os.getcwd()
        filename = QFileDialog.getSaveFileName(self.groupBox_7, 'Save file',
                                               current_path,
                                               "Excel Files (*.xlsx)")

        if filename[0] != '' and filename[0].endswith('xlsx'):
            df = pd.DataFrame(columns=['会员ID', '帐号', '帐号标识'])
            user_logins = select_user_login_list()
            for num, user in enumerate(user_logins):
                df.loc[num, '会员ID'] = user[3]
                df.loc[num, '帐号'] = user[1]
                df.loc[num, '帐号标识'] = user[2]
            df.to_excel(filename[0], index=False)

    def select_batch_address(self):
        current_path = os.getcwd()
        filename = QFileDialog.getOpenFileName(self.groupBox_batch_address,
                                               'Open file', current_path,
                                               "Excel Files (*.xlsx)")
        if filename[0] != '':
            self.batch_address_file = filename[0]
            self.qle_groupBox_batch_address.setText(self.batch_address_file)

    def batch_identify(self):
        xrowCount = self.tableWidget_groupBox_real_name.rowCount()
        for x in range(0, xrowCount):
            real_name = str(
                self.tableWidget_groupBox_real_name.item(x, 0).text())
            id_num = str(self.tableWidget_groupBox_real_name.item(x, 1).text())
            mobile = str(self.tableWidget_groupBox_real_name.item(x, 2).text())
            userinfo = get_userlogin_mobile(mobile)
            if userinfo:
                access_token = userinfo[2]
                token = get_token_by_mobile(mobile)
                if token:
                    succ, data = yemai_api.api_real_auth(
                        access_token, real_name, id_num)
                    if succ:
                        self.set_log_out('认证成功:{}'.format(mobile))
                        self.set_success_out('认证成功:{}'.format(mobile))
                        update_user_sm(self.comboBox.currentText(), '是')
                        self.user_list('YES')
                    else:
                        self.set_log_out('{}认证失败,原因:{}!!'.format(mobile, data))
                else:
                    self.set_log_out('{}输入错误,原因:{}!!'.format(
                        mobile, '注册手机未查询到'))
            else:
                self.set_log_out('{} 错误,原因:{}!!'.format(mobile, '该帐户未登录'))
        for x in range(0, xrowCount):
            self.tableWidget_groupBox_real_name.removeRow(x)
        self.tableWidget_groupBox_real_name.clearContents()
        self.qle_groupBox_real_name.setText("")
        pass

    def stop_surveillance(self):
        _translate = QtCore.QCoreApplication.translate
        self.monitor_status = False
        self.lineEdit_3_normal_order.setText(_translate("Object", "停止监控"))
        print("停止监控", self.monitor_status)
        pass

    def order_export(self):
        pass

    def order_clear(self):
        pass

    def self_pick_order(self):
        pass

    def self_pick_clear(self):
        pass

    def self_pick_export(self):
        pass

    def tabswitch(self, index):
        if index == 9:
            self.self_pick()
        if index == 8:
            self.pay_list()
        if index == 0:
            self.user_list('NO')
        if index == 2:
            self.proxy_list()
        if index == 4:
            self.user_nosm_list()
        if index == 3:
            # self.address_list()
            pass
        if index == 5:
            # self.order_list()
            pass
        if index == 6:
            self.xuanzhong_list()
        if index == 7:
            self.yuyue_success_list()

    def tab3click_kuai_yuliang(self):
        # 快代理余量按钮点击
        order_id = self.lineEdit_2.text()
        api_key = self.lineEdit_3.text()
        balance = kuai_api.get_dps_balance(order_id, api_key)
        self.label_17.setText("余量:" + str(balance))

    def tab3click_kuai_test(self):
        # 快代理余量按钮点击
        order_id = self.lineEdit_2.text()
        api_key = self.lineEdit_3.text()
        dps = kuai_api.get_dps(order_id, api_key, 5)
        self.textEdit.setText(str(dps))

    def tab2click_app_send_sms(self):
        mobile = self.lineEdit_12.text()
        if phone_check(mobile):
            self.lineEdit_18.setReadOnly(False)
            succ, data = yemai_api.api_sms(mobile)
            if succ:
                self.pushButton_15.setDisabled(True)
                self.tab2_log_list.append(
                    '已成功向{}发送验证码,请注意查收,输入验证码!'.format(mobile))
                self.set_log_out('已向{}发送验证码'.format(mobile))
            else:
                self.tab2_log_list.append('向{}发送验证码失败,原因:{}!!'.format(
                    mobile, data))
                self.set_log_out('向{}发送验证码失败,原因:{}!!'.format(mobile, data))
        else:
            self.tab2_log_list.append('手机格式错误:{}'.format(mobile))
        tab2_log_list_model = Qt.QStringListModel()
        tab2_log_list_model.setStringList(self.tab2_log_list)
        self.listView.setModel(tab2_log_list_model)

    def tab2click_app_login(self):
        if len(self.lineEdit_18.text()) > 4 and len(
                self.lineEdit_12.text()) == 11:
            # 简单判断手机号与注册码 是否ok
            self.tab2_log_list.append('准备登录:{},验证码:{}'.format(
                self.lineEdit_12.text(), self.lineEdit_18.text()))
            succ, data = yemai_api.api_login(self.lineEdit_12.text(),
                                             self.lineEdit_18.text())
            self.pushButton_15.setDisabled(False)
            if succ:
                self.tab2_log_list.append('成功登录:{}'.format(
                    self.lineEdit_12.text()))
                self.set_log_out('成功登录:{}'.format(self.lineEdit_12.text()))
                self.set_success_out('成功登录:{}'.format(self.lineEdit_12.text()))
                # 入库
                succ, member = yemai_api.api_huiyuan_list(data['accessToken'])
                update_user_login_token(self.lineEdit_12.text(),
                                        data['accessToken'], data['user_id'],
                                        '是' if member['is_autonym'] else '否',
                                        member['point'])
                create_user_login_success(self.lineEdit_12.text(),
                                          data['accessToken'], data['user_id'],
                                          '是' if member['is_autonym'] else '否',
                                          member['point'])
                self.user_list('YES')
                self.lineEdit_18.setText('')
                self.lineEdit_12.setText('')
            else:
                self.tab2_log_list.append('{}登录失败,原因:{}!!'.format(
                    self.lineEdit_12.text(), data))
                self.set_log_out('{}登录失败,原因:{}!!'.format(
                    self.lineEdit_12.text(), data))
        else:
            self.tab2_log_list.append('手机:{},验证码格式错误:{}'.format(
                self.lineEdit_12.text(), self.lineEdit_18.text()))
        tab2_log_list_model = Qt.QStringListModel()
        tab2_log_list_model.setStringList(self.tab2_log_list)
        self.listView.setModel(tab2_log_list_model)

    def tab2click_clear_log(self):
        self.tab2_log_list = []
        tab2_log_list_model = Qt.QStringListModel()
        tab2_log_list_model.setStringList(self.tab2_log_list)
        self.listView.setModel(tab2_log_list_model)

    def clear_all_log(self):
        self.log_list = []
        log_list_model = Qt.QStringListModel()
        log_list_model.setStringList(self.log_list)
        self.listView_4.setModel(log_list_model)

    def yuliu5_test(self):
        count = self.account_model.rowCount()

        for i in range(count):
            item = self.account_model.item(i, 0)

    def account_select_all(self):
        try:
            count = self.account_model.rowCount()
            if count > 0:
                if self.account_model.item(0, 0).checkState() == 0:
                    status = 2
                else:
                    status = 0
                for i in range(count):
                    item = self.account_model.item(i, 0)
                    item.setCheckState(status)
        except:
            pass

    def tab4click_app_shiming(self):
        if check_id_data(self.lineEdit_5.text()) and len(
                self.lineEdit_6.text()) >= 2 and phone_check(
            self.comboBox.currentText()):
            # 身份证, 姓名,token验证
            token = get_token_by_mobile(self.comboBox.currentText())
            if token:
                succ, data = yemai_api.api_real_auth(token,
                                                     self.lineEdit_6.text(),
                                                     self.lineEdit_5.text())
                if succ:
                    self.set_log_out('认证成功:{}'.format(self.lineEdit_6.text()))
                    self.set_success_out('认证成功:{}'.format(
                        self.lineEdit_6.text()))
                    # 入库
                    update_user_sm(self.comboBox.currentText(), '是')
                    self.user_list('YES')
                else:
                    self.set_log_out('{}认证失败,原因:{}!!'.format(
                        self.lineEdit_6.text(), data))
            else:
                self.set_log_out('{}输入错误,原因:{}!!'.format(
                    self.lineEdit_6.text(), '注册手机未查询到'))

        else:
            self.tab2_log_list.append('手机:{},验证码格式错误:{}'.format(
                self.lineEdit_12.text(), self.lineEdit_18.text()))
        tab2_log_list_model = Qt.QStringListModel()
        tab2_log_list_model.setStringList(self.tab2_log_list)
        self.listView.setModel(tab2_log_list_model)

    def tab6click_chahuo(self, Dialog):
        self.dialogsef = Dialog
        token, user_id = get_rand_token()
        succ, data = yemai_api.api_activity_goods(token, 145)
        print(succ, data)
        good_list = []
        if succ and data.get('goods', []):
            for goods in data.get('goods', []):
                goods_id = goods.get('goods_id')
                goods_name = goods.get('goods_name')
                goods_price = goods.get('goods_price', 0) / 100
                succ2, data = yemai_api.api_activity_good_detail(
                    token, 145, goods_id, user_id)
                reserve_first_time = get_time_str(
                    data.get('reserve_first_time'))  # 预约开始时间
                reserve_last_time = get_time_str(
                    data.get('reserve_last_time'))  # 预约结束时间
                pay_first_time = get_time_str(
                    data.get('pay_first_time'))  # 抢购起始时间
                pay_last_time = get_time_str(
                    data.get('pay_last_time'))  # 抢购起始时间
                if select_goods(goods_id):
                    update_goods(goods_id, goods_name, goods_price,
                                 reserve_first_time, reserve_last_time,
                                 pay_first_time, pay_last_time)
                else:
                    create_goods(goods_id, goods_name, goods_price,
                                 reserve_first_time, reserve_last_time,
                                 pay_first_time, pay_last_time)
                good_list.append(
                    (goods_id, goods_name, goods_price, reserve_first_time,
                     reserve_last_time, pay_first_time, pay_last_time))
                self.set_log_out('查到预约货品:{},预约时间{}到{}'.format(
                    goods_name, reserve_first_time, reserve_last_time))
                self.set_success_out('查到预约货品:{},预约时间{}到{}'.format(
                    goods_name, reserve_first_time, reserve_last_time))

        elif succ and not data.get('goods', []):
            self.set_log_out('目前还没有预约货品!!')
        else:
            self.set_log_out('预约查询失败,原因:{}!!'.format(data))

        model = QtGui.QStandardItemModel(1, 7)  # 存储任意结构数据
        model.setHorizontalHeaderLabels([
            'goods_id',
            '名称',
            '价格',
            '预约开始时间',
            '预约结束时间',
            '抢购开始时间',
            '抢购结束时间',
        ])
        for num, p in enumerate(good_list):
            goods_id = QtGui.QStandardItem(str(p[0]))
            goods_name = QtGui.QStandardItem(str(p[1]))
            goods_price = QtGui.QStandardItem(str(p[2]))
            reserve_first_time = QtGui.QStandardItem(str(p[3]))
            reserve_last_time = QtGui.QStandardItem(str(p[4]))
            pay_first_time = QtGui.QStandardItem(str(p[5]))
            pay_last_time = QtGui.QStandardItem(str(p[6]))

            model.setItem(num, 0, goods_id)
            model.setItem(num, 1, goods_name)
            model.setItem(num, 2, goods_price)
            model.setItem(num, 3, reserve_first_time)
            model.setItem(num, 4, reserve_last_time)
            model.setItem(num, 5, pay_first_time)
            model.setItem(num, 6, pay_last_time)
        self.dialogsef.tableView_19.setModel(model)

    def tab6click_yuyue(self):
        if len(self.lineEdit_16.text()) > 2 and len(
                self.comboBox_4.currentText()) > 6 and len(
            self.comboBox_3.currentText()) == 11:
            # gd_id, ad_id, 手机 验证
            token = get_token_by_mobile(self.comboBox_3.currentText())
            if not token:
                self.set_log_out('没有该手机账号!!')
                return
            mobile = self.comboBox_3.currentText()
            if select_yuyue_success(mobile, self.lineEdit_16.text()):
                yuyue = select_yuyue_success(mobile, self.lineEdit_16.text())
                last = yuyue[7]
                now = time.time()
                if get_timestamp(last) > now:
                    self.set_log_out('用户{}已经预约商品{}!!'.format(
                        mobile, self.lineEdit_16.text()))
                    return
            addr_id = self.comboBox_4.currentText().split('|')[-1]
            addr_name = self.comboBox_4.currentText().split('|')[1]
            addr_shouhuoren = self.comboBox_4.currentText().split('|')[0]
            succ, data = yemai_api.api_activity_good_yuyue(
                token, '145', addr_id, self.lineEdit_16.text())
            if succ:
                self.set_log_out('预约成功:{}'.format(mobile))
                self.set_success_out('预约成功:{}'.format(mobile))
                # 入库
                goods_info = select_goods(self.lineEdit_16.text())
                if not select_yuyue_success2(mobile, self.lineEdit_16.text(),
                                             goods_info[5], goods_info[6]):
                    create_yuyue_success(mobile, 145, self.lineEdit_16.text(),
                                         2, addr_id, goods_info[5],
                                         goods_info[6])
            else:
                self.set_log_out('预约失败,原因:{}!!'.format(data))
        else:
            self.set_log_out('预约输出信息错误!!')

    def tab1click_guoqi(self):
        try:
            count = self.account_model.rowCount()
            address = []
            for i in range(count):
                item = self.account_model.item(i, 0)
                if item.checkState() == 2:
                    token = self.account_model.item(i, 2).text()
                    shouji = self.account_model.item(i, 1).text()
                    succ, data = yemai_api.api_huiyuan_list(token)
                    if succ and data:
                        self.set_log_out('用户{}:token未过期,返回:{}'.format(
                            shouji, data))
                        point = data['point']
                        is_autonym = data['is_autonym']
                        update_user_point(shouji, token,
                                          '是' if is_autonym else '否', point)
                    else:
                        self.set_log_out('用户{}:token过期,返回:{}'.format(
                            shouji, data))
                        update_user_point(shouji, 'token已过期', '-', '-')
        except:
            pass
        self.user_list('YES')

    def tab1click_clear_guoqi(self):
        data = select_user_guoqi_list()
        for i in data:
            mobile = i[0]
            delete_user_by_mobile(mobile)
        self.user_list('YES')

    def timer_start(self):
        self.pushButton_24.setDisabled(True)
        self.lineEdit_8.setDisabled(True)
        self.lineEdit_9.setDisabled(True)
        self.label_50.setText('正在监控中...')

        qianggou_jiange = self.lineEdit_8.text()
        qianggou_ci = self.lineEdit_9.text()
        try:
            qianggou_jiange = int(qianggou_jiange)
            if qianggou_jiange < 500:
                qianggou_jiange = 500
        except:
            qianggou_jiange = 500
        try:
            qianggou_ci = int(qianggou_ci)
        except:
            qianggou_ci = 1000
        self.qianggou_cishu = qianggou_ci
        self.qianggou_jiange = qianggou_jiange

        count = self.yuyue_model.rowCount()
        self.jiankong_list = []
        self.jiankong_list1 = []
        self.jiankong_list2 = []
        self.jiankong_list3 = []
        self.jiankong_list4 = []

        for i in range(count):
            item = self.yuyue_model.item(i, 0)
            if item.checkState() == 2:
                mobile = self.yuyue_model.item(i, 0).text()
                token = get_token_by_mobile(mobile)
                activity_id = self.yuyue_model.item(i, 2).text()
                addr_id = self.yuyue_model.item(i, 5).text()
                goods_id = self.yuyue_model.item(i, 3).text()
                pay_date1 = self.yuyue_model.item(i, 6).text()
                pay_date2 = self.yuyue_model.item(i, 7).text()
                exe_stime = self.yuyue_model.item(i, 8).text()
                chenggong = self.yuyue_model.item(i, 9).text()
                cid = self.yuyue_model.item(i, 10).text()
                if len(self.jiankong_list) < self.jiankong_list_num:
                    self.jiankong_list.append(
                        (token, activity_id, addr_id, goods_id, pay_date1,
                         mobile, pay_date2, chenggong, exe_stime, cid,
                         self.qianggou_cishu))
                elif len(self.jiankong_list2) < self.jiankong_list_num:
                    self.jiankong_list2.append(
                        (token, activity_id, addr_id, goods_id, pay_date1,
                         mobile, pay_date2, chenggong, exe_stime, cid,
                         self.qianggou_cishu))
                elif len(self.jiankong_list3) < self.jiankong_list_num:
                    self.jiankong_list3.append(
                        (token, activity_id, addr_id, goods_id, pay_date1,
                         mobile, pay_date2, chenggong, exe_stime, cid,
                         self.qianggou_cishu))
                elif len(self.jiankong_list4) < self.jiankong_list_num:
                    self.jiankong_list4.append(
                        (token, activity_id, addr_id, goods_id, pay_date1,
                         mobile, pay_date2, chenggong, exe_stime, cid,
                         self.qianggou_cishu))
                elif len(self.jiankong_list5) < self.jiankong_list_num:
                    self.jiankong_list5.append(
                        (token, activity_id, addr_id, goods_id, pay_date1,
                         mobile, pay_date2, chenggong, exe_stime, cid,
                         self.qianggou_cishu))

        self.timer_jiankong = QtCore.QTimer()
        self.timer_jiankong2 = QtCore.QTimer()
        self.timer_jiankong3 = QtCore.QTimer()
        self.timer_jiankong4 = QtCore.QTimer()
        self.timer_jiankong5 = QtCore.QTimer()
        self.timer_jiankong.timeout.connect(self.timerexe)
        self.timer_jiankong2.timeout.connect(self.timerexe2)
        self.timer_jiankong3.timeout.connect(self.timerexe3)
        self.timer_jiankong4.timeout.connect(self.timerexe4)
        self.timer_jiankong5.timeout.connect(self.timerexe5)
        self.timer_jiankong.start(self.qianggou_jiange)
        self.timer_jiankong2.start(self.qianggou_jiange)
        self.timer_jiankong3.start(self.qianggou_jiange)
        self.timer_jiankong4.start(self.qianggou_jiange)
        self.timer_jiankong5.start(self.qianggou_jiange)
        x = []
        x.extend(self.jiankong_list)
        x.extend(self.jiankong_list2)
        x.extend(self.jiankong_list3)
        x.extend(self.jiankong_list4)
        x.extend(self.jiankong_list5)

        for i in x:
            yuan_api.add_dingshi(i[3], i[8], i[0], i[5])

    def timer_stop(self):
        self.pushButton_24.setDisabled(False)
        self.lineEdit_8.setDisabled(False)
        self.lineEdit_9.setDisabled(False)
        self.label_50.setText('监控已停止...')
        self.jiankong_cishu = 0
        self.jiankong_cishu2 = 0
        self.jiankong_cishu3 = 0
        self.jiankong_cishu4 = 0
        self.jiankong_cishu5 = 0
        self.timer_jiankong.stop()
        self.timer_jiankong2.stop()
        self.timer_jiankong3.stop()
        self.timer_jiankong4.stop()
        self.timer_jiankong5.stop()

    def timerexe(self):
        t = threading.Thread(target=self.threading_timerexe)
        t.daemon = True
        t.start()

    def timerexe2(self):
        t = threading.Thread(target=self.threading_timerexe2)
        t.daemon = True
        t.start()

    def timerexe3(self):
        t = threading.Thread(target=self.threading_timerexe3)
        t.daemon = True
        t.start()

    def timerexe4(self):
        t = threading.Thread(target=self.threading_timerexe4)
        t.daemon = True
        t.start()

    def timerexe5(self):
        t = threading.Thread(target=self.threading_timerexe5)
        t.daemon = True
        t.start()

    def threading_timerexe(self):
        now = time.time()
        now_str = get_time_str(now)
        for jk in self.jiankong_list:
            pay_date = jk[4]
            mobile = jk[5]
            token = jk[0]
            activity_id = jk[1]
            addr_id = jk[2]
            goods_id = jk[3]
            pay_date2 = jk[6]
            is_success = jk[7]
            exe_stime = jk[8]
            cid = jk[9]
            cishu = jk[10]
            pay_date_timestamp = get_timestamp(pay_date)
            pay_date2_timestamp = get_timestamp(pay_date2)
            exe_stime_timestamp = get_timestamp(exe_stime)
            last_t = pay_date_timestamp - pay_date2_timestamp
            shengyu = int((exe_stime_timestamp - now))
            if self.use_proxy and self.checkBox_6.checkState() == 2:
                use_proxy = True
                ip = kuai_api.get_dps(self.proxy_order_id, self.proxy_api_key,
                                      1)
                use_proxy_str = '当前代理ip:{}(由于代理ip网络质量不一,可能会导致抢购延时!)'.format(ip)
            else:
                ip = ''
                use_proxy = False
                use_proxy_str = '当前未使用代理(如需使用,请在代理配置页点击请求测试并在当前页选中使用!)'

            if is_success == '是':
                self.set_log_out(
                    '组1(已成功完成活动抢购,已成功)监控详情:用户{}的商品id:{}已经抢购成功,当前监控时间:{}'.
                        format(mobile, goods_id, now_str, use_proxy_str))
                self.set_success_out(
                    '组1(已成功完成活动抢购,已成功)监控详情:用户{}的商品id:{}已经抢购成功,当前监控时间:{}'.
                        format(mobile, goods_id, now_str, use_proxy_str))

                continue

            if exe_stime_timestamp > pay_date2_timestamp:
                self.set_log_out(
                    '组1(当前设置的开始监控时间在抢购活动结束之外)监控详情:用户{}的商品id:{}可能配置了错误的监控时间,当前监控时间:{}'
                        .format(mobile, goods_id, now_str, use_proxy_str))
                continue
            if shengyu <= 0 and is_success != '是':
                if self.jiankong_cishu > cishu:
                    self.set_log_out(
                        '组1(当前抢购次数已达到{}次)监控详情:用户{}的商品id:{}已完成{}次抢购,当前监控时间:{}'.
                            format(cishu, mobile, goods_id, cishu, now_str,
                                   use_proxy_str))
                    continue
                if use_proxy and ip:
                    y = YeMaiAPI(ip, 1)
                    succ, data = y.api_yuyue_create_order(
                        token, activity_id, addr_id, goods_id)

                else:
                    succ, data = yemai_api.api_yuyue_create_order(
                        token, activity_id, addr_id, goods_id)
                self.jiankong_cishu += 1

                if succ:
                    self.set_log_out(
                        '组1(已到开始时间,正在发起抢购:已抢购成功,完成抢购)监控详情:用户{}抢购成功,app返回成功数据:({})。当前监控时间:{},代理:{}'
                            .format(mobile, data, now_str, use_proxy_str))
                    self.set_success_out(
                        '组1(已到开始时间,正在发起抢购:已抢购成功,完成抢购)监控详情:用户{}抢购成功,app返回成功数据:({})。当前监控时间:{},代理:{}'
                            .format(mobile, data, now_str, use_proxy_str))
                    with open('./logs/success.txt', 'a') as f:
                        f.write(str(data) + '\n')
                    try:
                        yuan_api.qj_success(mobile, str(data) + ''.join(jk))
                    except:
                        pass
                    # 入库
                    update_yuyue_success(mobile, goods_id, pay_date, '是')
                    if self.yuyue_shaixuan:
                        self.shaixuan_yuyue_succ()
                    else:
                        self.yuyue_success_list()
                else:
                    self.set_log_out(
                        '组1(已到开始时间,正在发起抢购:抢购失败)监控详情:用户{}抢购失败,app返回原因:({})。当前监控时间:{},代理:{}'
                            .format(mobile, data, now_str, use_proxy_str))
            else:
                self.set_log_out(
                    '组1(正在监控,准备抢购)监控详情:用户{}距离抢购还有{}秒开始,当前时间:{}'.format(
                        mobile, shengyu, now_str, use_proxy_str))

    def threading_timerexe2(self):
        now = time.time()
        now_str = get_time_str(now)
        for jk in self.jiankong_list2:
            pay_date = jk[4]
            mobile = jk[5]
            token = jk[0]
            activity_id = jk[1]
            addr_id = jk[2]
            goods_id = jk[3]
            pay_date2 = jk[6]
            is_success = jk[7]
            exe_stime = jk[8]
            cid = jk[9]
            cishu = jk[10]
            pay_date_timestamp = get_timestamp(pay_date)
            pay_date2_timestamp = get_timestamp(pay_date2)
            exe_stime_timestamp = get_timestamp(exe_stime)
            last_t = pay_date_timestamp - pay_date2_timestamp
            shengyu = int((exe_stime_timestamp - now))
            if self.use_proxy and self.checkBox_6.checkState() == 2:
                use_proxy = True
                ip = kuai_api.get_dps(self.proxy_order_id, self.proxy_api_key,
                                      1)
                use_proxy_str = '当前代理ip:{}(由于代理ip网络质量不一,可能会导致抢购延时!)'.format(ip)
            else:
                ip = ''
                use_proxy = False
                use_proxy_str = '当前未使用代理(如需使用,请在代理配置页点击请求测试并在当前页选中使用!)'

            if is_success == '是':
                self.set_log_out(
                    '组2(已成功完成活动抢购,已成功)监控详情:用户{}的商品id:{}已经抢购成功,当前监控时间:{}'.
                        format(mobile, goods_id, now_str, use_proxy_str))
                self.set_success_out(
                    '组2(已成功完成活动抢购,已成功)监控详情:用户{}的商品id:{}已经抢购成功,当前监控时间:{}'.
                        format(mobile, goods_id, now_str, use_proxy_str))

                continue

            if exe_stime_timestamp > pay_date2_timestamp:
                self.set_log_out(
                    '组2(当前设置的开始监控时间在抢购活动结束之外)监控详情:用户{}的商品id:{}可能配置了错误的监控时间,当前监控时间:{}'
                        .format(mobile, goods_id, now_str, use_proxy_str))
                continue
            if shengyu <= 0 and is_success != '是':
                if self.jiankong_cishu2 > cishu:
                    self.set_log_out(
                        '组2(当前抢购次数已达到{}次)监控详情:用户{}的商品id:{}已完成{}次抢购,当前监控时间:{}'.
                            format(cishu, mobile, goods_id, cishu, now_str,
                                   use_proxy_str))
                    continue
                if use_proxy and ip:
                    y = YeMaiAPI(ip, 1)
                    succ, data = y.api_yuyue_create_order(
                        token, activity_id, addr_id, goods_id)

                else:
                    succ, data = yemai_api.api_yuyue_create_order(
                        token, activity_id, addr_id, goods_id)
                self.jiankong_cishu2 += 1

                if succ:
                    self.set_log_out(
                        '组2(已到开始时间,正在发起抢购:已抢购成功,完成抢购)监控详情:用户{}抢购成功,app返回成功数据:({})。当前监控时间:{},代理:{}'
                            .format(mobile, data, now_str, use_proxy_str))
                    self.set_success_out(
                        '组2(已到开始时间,正在发起抢购:已抢购成功,完成抢购)监控详情:用户{}抢购成功,app返回成功数据:({})。当前监控时间:{},代理:{}'
                            .format(mobile, data, now_str, use_proxy_str))
                    with open('success.txt', 'a') as f:
                        f.write(str(data) + '\n')
                    try:
                        yuan_api.qj_success(mobile, str(data) + ''.join(jk))
                    except:
                        pass
                    # 入库
                    update_yuyue_success(mobile, goods_id, pay_date, '是')
                    if self.yuyue_shaixuan:
                        self.shaixuan_yuyue_succ()
                    else:
                        self.yuyue_success_list()
                else:
                    self.set_log_out(
                        '组2(已到开始时间,正在发起抢购:抢购失败)监控详情:用户{}抢购失败,app返回原因:({})。当前监控时间:{},代理:{}'
                            .format(mobile, data, now_str, use_proxy_str))
            else:
                self.set_log_out(
                    '组2(正在监控,准备抢购)监控详情:用户{}距离抢购还有{}秒开始,当前时间:{}'.format(
                        mobile, shengyu, now_str, use_proxy_str))

    def threading_timerexe3(self):
        now = time.time()
        now_str = get_time_str(now)
        for jk in self.jiankong_list3:
            pay_date = jk[4]
            mobile = jk[5]
            token = jk[0]
            activity_id = jk[1]
            addr_id = jk[2]
            goods_id = jk[3]
            pay_date2 = jk[6]
            is_success = jk[7]
            exe_stime = jk[8]
            cid = jk[9]
            cishu = jk[10]
            pay_date_timestamp = get_timestamp(pay_date)
            pay_date2_timestamp = get_timestamp(pay_date2)
            exe_stime_timestamp = get_timestamp(exe_stime)
            last_t = pay_date_timestamp - pay_date2_timestamp
            shengyu = int((exe_stime_timestamp - now))
            if self.use_proxy and self.checkBox_6.checkState() == 2:
                use_proxy = True
                ip = kuai_api.get_dps(self.proxy_order_id, self.proxy_api_key,
                                      1)
                use_proxy_str = '当前代理ip:{}(由于代理ip网络质量不一,可能会导致抢购延时!)'.format(ip)
            else:
                ip = ''
                use_proxy = False
                use_proxy_str = '当前未使用代理(如需使用,请在代理配置页点击请求测试并在当前页选中使用!)'

            if is_success == '是':
                self.set_log_out(
                    '组3(已成功完成活动抢购,已成功)监控详情:用户{}的商品id:{}已经抢购成功,当前监控时间:{}'.
                        format(mobile, goods_id, now_str, use_proxy_str))
                self.set_success_out(
                    '组3(已成功完成活动抢购,已成功)监控详情:用户{}的商品id:{}已经抢购成功,当前监控时间:{}'.
                        format(mobile, goods_id, now_str, use_proxy_str))

                continue

            if exe_stime_timestamp > pay_date2_timestamp:
                self.set_log_out(
                    '组3(当前设置的开始监控时间在抢购活动结束之外)监控详情:用户{}的商品id:{}可能配置了错误的监控时间,当前监控时间:{}'
                        .format(mobile, goods_id, now_str, use_proxy_str))
                continue
            if shengyu <= 0 and is_success != '是':
                if self.jiankong_cishu3 > cishu:
                    self.set_log_out(
                        '组3(当前抢购次数已达到{}次)监控详情:用户{}的商品id:{}已完成{}次抢购,当前监控时间:{}'.
                            format(cishu, mobile, goods_id, cishu, now_str,
                                   use_proxy_str))
                    continue
                if use_proxy and ip:
                    y = YeMaiAPI(ip, 1)
                    succ, data = y.api_yuyue_create_order(
                        token, activity_id, addr_id, goods_id)

                else:
                    succ, data = yemai_api.api_yuyue_create_order(
                        token, activity_id, addr_id, goods_id)
                self.jiankong_cishu3 += 1
                if succ:
                    self.set_log_out(
                        '组3(已到开始时间,正在发起抢购:已抢购成功,完成抢购)监控详情:用户{}抢购成功,app返回成功数据:({})。当前监控时间:{},代理:{}'
                            .format(mobile, data, now_str, use_proxy_str))
                    self.set_success_out(
                        '组3(已到开始时间,正在发起抢购:已抢购成功,完成抢购)监控详情:用户{}抢购成功,app返回成功数据:({})。当前监控时间:{},代理:{}'
                            .format(mobile, data, now_str, use_proxy_str))
                    try:
                        yuan_api.qj_success(mobile, str(data) + ''.join(jk))
                    except:
                        pass
                    # 入库
                    update_yuyue_success(mobile, goods_id, pay_date, '是')
                    if self.yuyue_shaixuan:
                        self.shaixuan_yuyue_succ()
                    else:
                        self.yuyue_success_list()
                else:
                    self.set_log_out(
                        '组3(已到开始时间,正在发起抢购:抢购失败)监控详情:用户{}抢购失败,app返回原因:({})。当前监控时间:{},代理:{}'
                            .format(mobile, data, now_str, use_proxy_str))
            else:
                self.set_log_out(
                    '组3(正在监控,准备抢购)监控详情:用户{}距离抢购还有{}秒开始,当前时间:{}'.format(
                        mobile, shengyu, now_str, use_proxy_str))

    def threading_timerexe4(self):
        now = time.time()
        now_str = get_time_str(now)
        for jk in self.jiankong_list4:
            pay_date = jk[4]
            mobile = jk[5]
            token = jk[0]
            activity_id = jk[1]
            addr_id = jk[2]
            goods_id = jk[3]
            pay_date2 = jk[6]
            is_success = jk[7]
            exe_stime = jk[8]
            cid = jk[9]
            cishu = jk[10]
            pay_date_timestamp = get_timestamp(pay_date)
            pay_date2_timestamp = get_timestamp(pay_date2)
            exe_stime_timestamp = get_timestamp(exe_stime)
            last_t = pay_date_timestamp - pay_date2_timestamp
            shengyu = int((exe_stime_timestamp - now))
            if self.use_proxy and self.checkBox_6.checkState() == 2:
                use_proxy = True
                ip = kuai_api.get_dps(self.proxy_order_id, self.proxy_api_key,
                                      1)
                use_proxy_str = '当前代理ip:{}(由于代理ip网络质量不一,可能会导致抢购延时!)'.format(ip)
            else:
                ip = ''
                use_proxy = False
                use_proxy_str = '当前未使用代理(如需使用,请在代理配置页点击请求测试并在当前页选中使用!)'

            if is_success == '是':
                self.set_log_out(
                    '组4(已成功完成活动抢购,已成功)监控详情:用户{}的商品id:{}已经抢购成功,当前监控时间:{}'.
                        format(mobile, goods_id, now_str, use_proxy_str))
                self.set_success_out(
                    '组4(已成功完成活动抢购,已成功)监控详情:用户{}的商品id:{}已经抢购成功,当前监控时间:{}'.
                        format(mobile, goods_id, now_str, use_proxy_str))

                continue

            if exe_stime_timestamp > pay_date2_timestamp:
                self.set_log_out(
                    '组4(当前设置的开始监控时间在抢购活动结束之外)监控详情:用户{}的商品id:{}可能配置了错误的监控时间,当前监控时间:{}'
                        .format(mobile, goods_id, now_str, use_proxy_str))
                continue
            if shengyu <= 0 and is_success != '是':
                if self.jiankong_cishu4 > cishu:
                    self.set_log_out(
                        '组4(当前抢购次数已达到{}次)监控详情:用户{}的商品id:{}已完成{}次抢购,当前监控时间:{}'.
                            format(cishu, mobile, goods_id, cishu, now_str,
                                   use_proxy_str))
                    continue
                if use_proxy and ip:
                    y = YeMaiAPI(ip, 1)
                    succ, data = y.api_yuyue_create_order(
                        token, activity_id, addr_id, goods_id)

                else:
                    succ, data = yemai_api.api_yuyue_create_order(
                        token, activity_id, addr_id, goods_id)
                self.jiankong_cishu4 += 1

                if succ:
                    self.set_log_out(
                        '组4(已到开始时间,正在发起抢购:已抢购成功,完成抢购)监控详情:用户{}抢购成功,app返回成功数据:({})。当前监控时间:{},代理:{}'
                            .format(mobile, data, now_str, use_proxy_str))
                    self.set_success_out(
                        '组4(已到开始时间,正在发起抢购:已抢购成功,完成抢购)监控详情:用户{}抢购成功,app返回成功数据:({})。当前监控时间:{},代理:{}'
                            .format(mobile, data, now_str, use_proxy_str))
                    with open('success.txt', 'a') as f:
                        f.write(str(data) + '\n')
                    try:
                        yuan_api.qj_success(mobile, str(data) + ''.join(jk))
                    except:
                        pass
                    # 入库
                    update_yuyue_success(mobile, goods_id, pay_date, '是')
                    if self.yuyue_shaixuan:
                        self.shaixuan_yuyue_succ()
                    else:
                        self.yuyue_success_list()
                else:
                    self.set_log_out(
                        '组4(已到开始时间,正在发起抢购:抢购失败)监控详情:用户{}抢购失败,app返回原因:({})。当前监控时间:{},代理:{}'
                            .format(mobile, data, now_str, use_proxy_str))
            else:
                self.set_log_out(
                    '组4(正在监控,准备抢购)监控详情:用户{}距离抢购还有{}秒开始,当前时间:{}'.format(
                        mobile, shengyu, now_str, use_proxy_str))

    def threading_timerexe5(self):
        now = time.time()
        now_str = get_time_str(now)
        for jk in self.jiankong_list5:
            pay_date = jk[4]
            mobile = jk[5]
            token = jk[0]
            activity_id = jk[1]
            addr_id = jk[2]
            goods_id = jk[3]
            pay_date2 = jk[6]
            is_success = jk[7]
            exe_stime = jk[8]
            cid = jk[9]
            cishu = jk[10]
            pay_date_timestamp = get_timestamp(pay_date)
            pay_date2_timestamp = get_timestamp(pay_date2)
            exe_stime_timestamp = get_timestamp(exe_stime)
            last_t = pay_date_timestamp - pay_date2_timestamp
            shengyu = int((exe_stime_timestamp - now))
            if self.use_proxy and self.checkBox_6.checkState() == 2:
                use_proxy = True
                ip = kuai_api.get_dps(self.proxy_order_id, self.proxy_api_key,
                                      1)
                use_proxy_str = '当前代理ip:{}(由于代理ip网络质量不一,可能会导致抢购延时!)'.format(ip)
            else:
                ip = ''
                use_proxy = False
                use_proxy_str = '当前未使用代理(如需使用,请在代理配置页点击请求测试并在当前页选中使用!)'

            if is_success == '是':
                self.set_log_out(
                    '组5(已成功完成活动抢购,已成功)监控详情:用户{}的商品id:{}已经抢购成功,当前监控时间:{}'.
                        format(mobile, goods_id, now_str, use_proxy_str))
                self.set_success_out(
                    '组5(已成功完成活动抢购,已成功)监控详情:用户{}的商品id:{}已经抢购成功,当前监控时间:{}'.
                        format(mobile, goods_id, now_str, use_proxy_str))

                continue

            if exe_stime_timestamp > pay_date2_timestamp:
                self.set_log_out(
                    '组5(当前设置的开始监控时间在抢购活动结束之外)监控详情:用户{}的商品id:{}可能配置了错误的监控时间,当前监控时间:{}'
                        .format(mobile, goods_id, now_str, use_proxy_str))
                continue
            if shengyu <= 0 and is_success != '是':
                if self.jiankong_cishu5 > cishu:
                    self.set_log_out(
                        '组5(当前抢购次数已达到{}次)监控详情:用户{}的商品id:{}已完成{}次抢购,当前监控时间:{}'.
                            format(cishu, mobile, goods_id, cishu, now_str,
                                   use_proxy_str))
                    continue
                if use_proxy and ip:
                    y = YeMaiAPI(ip, 1)
                    succ, data = y.api_yuyue_create_order(
                        token, activity_id, addr_id, goods_id)

                else:
                    succ, data = yemai_api.api_yuyue_create_order(
                        token, activity_id, addr_id, goods_id)
                self.jiankong_cishu5 += 1

                if succ:
                    self.set_log_out(
                        '组5(已到开始时间,正在发起抢购:已抢购成功,完成抢购)监控详情:用户{}抢购成功,app返回成功数据:({})。当前监控时间:{},代理:{}'
                            .format(mobile, data, now_str, use_proxy_str))
                    self.set_success_out(
                        '组5(已到开始时间,正在发起抢购:已抢购成功,完成抢购)监控详情:用户{}抢购成功,app返回成功数据:({})。当前监控时间:{},代理:{}'
                            .format(mobile, data, now_str, use_proxy_str))
                    with open('success.txt', 'a') as f:
                        f.write(str(data) + '\n')
                    try:
                        yuan_api.qj_success(mobile, str(data) + ''.join(jk))
                    except:
                        pass
                    # 入库
                    update_yuyue_success(mobile, goods_id, pay_date, '是')
                    if self.yuyue_shaixuan:
                        self.shaixuan_yuyue_succ()
                    else:
                        self.yuyue_success_list()
                else:
                    self.set_log_out(
                        '组5(已到开始时间,正在发起抢购:抢购失败)监控详情:用户{}抢购失败,app返回原因:({})。当前监控时间:{},代理:{}'
                            .format(mobile, data, now_str, use_proxy_str))
            else:
                self.set_log_out(
                    '组5(正在监控,准备抢购)监控详情:用户{}距离抢购还有{}秒开始,当前时间:{}'.format(
                        mobile, shengyu, now_str, use_proxy_str))

    def addr_add(self):
        ssq = self.lineEdit_11.text()
        xm = self.lineEdit_13.text() or '马老师'
        shsj = self.lineEdit_14.text()
        mobile = self.comboBox_2.currentText()
        xq = self.lineEdit.text()
        token = get_token_by_mobile(mobile)
        if not shsj:
            shsj = mobile
        if ssq and len(token) == 64 and xq and phone_check(shsj):
            succ, data = yemai_api.api_address_add(token, ssq, xq, shsj, xm)
            self.address_list()
        else:
            self.set_log_out('地址输入信息有误!请自查输入信息')

    def address_list(self):
        try:
            sjs = []
            self.comboBox_2.clear()
            sj = select_user_login_list()
            for i in sj:
                sjs.append(i[1])
            self.comboBox_2.addItems(sjs)
            count = self.account_model.rowCount()
            address = []
            for i in range(count):
                item = self.account_model.item(i, 0)
                if item.checkState() == 2:
                    token = self.account_model.item(i, 2).text()
                    shouji = self.account_model.item(i, 1).text()
                    succ, data = yemai_api.api_address_list(token)
                    self.set_log_out('获取用户地址{}:信息:{}'.format(shouji, data))
                    if succ and data.get('list'):
                        for i in data.get('list', []):
                            addr_id = i['addr_id']
                            name = i['name']
                            addr = i['mapAddr']  # i['addrdetail']
                            mobile = i['mobile']
                            address.append(
                                (shouji, addr_id, name, addr, mobile, token))
                    if succ and not data.get('list'):
                        addr_id = '还没有创建地址'
                        name = '还没有创建'
                        addr = '还没有创建'
                        mobile = '还没有创建'
                        address.append(
                            (shouji, addr_id, name, addr, mobile, token))

            model = QtGui.QStandardItemModel(1, 6)  # 存储任意结构数据
            model.setHorizontalHeaderLabels(
                ['手机号', 'addr_id', '收货地址', '收货人', '收货手机', 'token'])

            for num, p in enumerate(address):
                shouji = QtGui.QStandardItem(str(p[0]))
                addr_id = QtGui.QStandardItem(str(p[1]))
                addr = QtGui.QStandardItem(str(p[2]))
                name = QtGui.QStandardItem(str(p[3]))
                mobile = QtGui.QStandardItem(str(p[4]))
                token = QtGui.QStandardItem(str(p[5]))

                model.setItem(num, 0, shouji)
                model.setItem(num, 1, addr_id)
                model.setItem(num, 3, addr)
                model.setItem(num, 2, name)
                model.setItem(num, 4, mobile)
                model.setItem(num, 5, token)
            self.dialogsef.tableView_11.setModel(model)
        except:
            pass

    def proxy_test(self):
        self.proxy_order_id = self.dialogsef.lineEdit_2.text()
        self.proxy_api_key = self.dialogsef.lineEdit_3.text()
        dps = kuai_api.get_dps(self.proxy_order_id, self.proxy_api_key, 1)
        res = test_ip_proxy(dps, 2)
        if res:
            self.label_45.setText('测试通过,配置使用!!')
            self.use_proxy = True
            self.pushButton_20.setDisabled(True)
            self.label_16.setText('已配置使用!')

        else:
            self.label_45.setText('测试未通过,请配置白名单或点击重试!')
            self.use_proxy = False

    def stimer_change(self):
        count = self.yuyue_model.rowCount()
        for i in range(count):
            item = self.yuyue_model.item(i, 0)
            if item.checkState() == 2:
                cid = self.yuyue_model.item(i, 10).text()
                s_time = self.dateTimeEdit.text()
                update_yuyue_success_stime(cid, s_time)
        if self.yuyue_shaixuan:
            self.shaixuan_yuyue_succ()
        else:
            self.yuyue_success_list()

    def shaixuan_yuyue_succ(self):
        self.yuyue_shaixuan = True
        self.yuyue_model = QtGui.QStandardItemModel(1, 8)  # 存储任意结构数据
        self.yuyue_model.setHorizontalHeaderLabels([
            '手机号', '是否过期', '活动id', '商品id', '数量', 'addr_id', '抢购起始时间', '抢购结束时间',
            '开始监控时间', '是否成功抢购', 'id'
        ])

        proxies = select_yuyue_all()
        c = 0
        for num, p in enumerate(proxies):
            pay_last_time = get_timestamp(p[7])
            now = time.time()
            rid = QtGui.QStandardItem(str(p[1]))
            r1 = QtGui.QStandardItem(str(p[0]))
            if pay_last_time > now:
                guoqi = '抢购未过期'
                r1.setCheckable(True)
                r1.setCheckState(2)
                r2 = QtGui.QStandardItem(str(guoqi))
                r3 = QtGui.QStandardItem(str(p[2]))
                r4 = QtGui.QStandardItem(str(p[3]))
                r5 = QtGui.QStandardItem(str(p[4]))
                r6 = QtGui.QStandardItem(str(p[5]))
                r7 = QtGui.QStandardItem(str(p[6]))
                r8 = QtGui.QStandardItem(str(p[7]))
                r9 = QtGui.QStandardItem(str(p[9]))
                r10 = QtGui.QStandardItem(str(p[8]))

                self.yuyue_model.setItem(num - c, 0, r1)
                self.yuyue_model.setItem(num - c, 1, r2)
                self.yuyue_model.setItem(num - c, 2, r3)
                self.yuyue_model.setItem(num - c, 3, r4)
                self.yuyue_model.setItem(num - c, 4, r5)
                self.yuyue_model.setItem(num - c, 5, r6)
                self.yuyue_model.setItem(num - c, 6, r7)
                self.yuyue_model.setItem(num - c, 7, r8)
                self.yuyue_model.setItem(num - c, 8, r9)
                self.yuyue_model.setItem(num - c, 9, r10)
                self.yuyue_model.setItem(num - c, 10, rid)
            else:
                c += 1
        self.dialogsef.tableView_5.setModel(self.yuyue_model)
        self.dialogsef.tableView_5.resizeColumnsToContents()  # 自适应

    def order_qb(self):
        self.order_list()

    def order_fk(self):
        self.order_list('待付款')

    def order_ps(self):
        self.order_list('待配送')

    def order_wc(self):
        self.order_list('已完成')

    def order_gb(self):
        self.order_list('已关闭')

    def addr_get(self):
        mobile = self.comboBox_3.currentText()
        if len(mobile) < 10:
            return
        token = get_token_by_mobile(mobile)

        succ, data = yemai_api.api_address_list(token)
        address = []
        self.comboBox_4.clear()
        self.set_log_out('获取用户地址{}:信息:{}'.format(mobile, data))
        if succ and data.get('list'):
            for i in data.get('list', []):
                addr_id = i['addr_id']
                name = i['name']
                addr = i['mapAddr']  # i['addrdetail']
                mobile = i['mobile']
                address.append('|'.join([name, addr, str(addr_id)]))
        if succ and not data.get('list'):
            addr_id = '还没有创建地址'
            name = '还没有创建'
            addr = '还没有创建'
            mobile = '还没有创建'
            address.append('|'.join([name, addr, str(addr_id)]))
        self.comboBox_4.addItems(address)

    def set_log_out_exe(self, Dialog):
        self.dialogsef = Dialog
        # 窗体输出显示
        self.dialogsef.log_model.setStringList(self.log_list)
        self.dialogsef.listView_4.setModel(self.log_model)

    def send_yuan_check(self):
        code = yuan_api.exe_check()

    def user_list(self, Dialog, refresh='YES'):
        self.dialogsef = Dialog
        if self.dialogsef.account_model.rowCount() == 1 and self.dialogsef.account_model.item(
                0, 0) == None:
            # 没有数据,
            self.dialogsef.account_model = QtGui.QStandardItemModel(1, 7)  # 存储任意结构数据
            self.dialogsef.account_model.setHorizontalHeaderLabels(
                ['id号', '手机号码', 'token', 'app用户id', '是否实名', '积分', '登录是否过期'])
            user_logins = select_user_login_list()
            for num, user in enumerate(user_logins):

                cid = QtGui.QStandardItem(str(user[0]))
                mobile = QtGui.QStandardItem(user[1])
                token = QtGui.QStandardItem(user[2])
                user_id = QtGui.QStandardItem(str(user[3]))
                is_sm = QtGui.QStandardItem(str(user[4]))
                jifen = QtGui.QStandardItem(str(user[5]))
                if len(user[2]) == 64:
                    guoqi = '登录未过期'
                else:
                    guoqi = '登录已过期'
                x = QtGui.QStandardItem(guoqi)
                x.setEditable(False)
                token.setEditable(False)
                cid.setCheckable(True)
                cid.setEditable(False)
                self.dialogsef.account_model.setItem(num, 0, cid)
                self.dialogsef.account_model.setItem(num, 1, mobile)
                self.dialogsef.account_model.setItem(num, 2, token)
                self.dialogsef.account_model.setItem(num, 3, user_id)
                self.dialogsef.account_model.setItem(num, 4, is_sm)
                self.dialogsef.account_model.setItem(num, 5, jifen)
                self.dialogsef.account_model.setItem(num, 6, x)
        else:
            # 有数据
            if refresh == 'YES':
                self.dialogsef.account_model = QtGui.QStandardItemModel(1, 7)  # 存储任意结构数据
                self.dialogsef.account_model.setHorizontalHeaderLabels([
                    'id号', '手机号码', 'token', 'app用户id', '是否实名', '积分', '登录是否过期'
                ])
                user_logins = select_user_login_list()
                for num, user in enumerate(user_logins):
                    cid = QtGui.QStandardItem(str(user[0]))
                    mobile = QtGui.QStandardItem(user[1])
                    token = QtGui.QStandardItem(user[2])
                    user_id = QtGui.QStandardItem(str(user[3]))
                    is_sm = QtGui.QStandardItem(str(user[4]))
                    jifen = QtGui.QStandardItem(str(user[5]))
                    if len(user[2]) == 64:
                        guoqi = '登录未过期'
                    else:
                        guoqi = '登录已过期'
                    x = QtGui.QStandardItem(guoqi)
                    x.setEditable(False)
                    cid.setCheckable(True)
                    token.setEditable(False)
                    cid.setEditable(False)
                    self.dialogsef.account_model.setItem(num, 0, cid)
                    self.dialogsef.account_model.setItem(num, 1, mobile)
                    self.dialogsef.account_model.setItem(num, 2, token)
                    self.dialogsef.account_model.setItem(num, 3, user_id)
                    self.dialogsef.account_model.setItem(num, 4, is_sm)
                    self.dialogsef.account_model.setItem(num, 5, jifen)
                    self.dialogsef.account_model.setItem(num, 6, x)
        self.dialogsef.tableView_3.setModel(self.dialogsef.account_model)

    def set_log_out(self, log_string):
        # 窗体输出显示
        self.log_list.append(log_string)

    def set_success_out(self, log_string):
        # 窗体成功输出显示
        self.success_log_list.append(log_string)
        log_list_model = Qt.QStringListModel()
        log_list_model.setStringList(self.success_log_list)
        self.listView_2.setModel(log_list_model)

    def sms_select(self, Dialog):
        self.dialogsef = Dialog
        phonenumber = ''
        try:
            count = self.account_model.rowCount()
            address = []
            for i in range(count):
                item = self.dialogsef.account_model.item(i, 0)
                if item.checkState() == 2:
                    mobile = self.dialogsef.account_model.item(i, 1).text()
                    print("mobile", mobile)
                    phonenumber = mobile
                    succ, data = yemai_api.api_sms(mobile)
                    if succ:
                        self.set_log_out(
                            '已成功向{}发送验证码,请注意查收,输入验证码!'.format(mobile))
                    else:
                        self.tab2_log_list.append('向{}发送验证码失败,原因:{}!!'.format(
                            mobile, data))
                        self.set_log_out('向{}发送验证码失败,原因:{}!!'.format(
                            mobile, data))
                    break
        except:
            pass
        self.tip_window = QtWidgets.QMainWindow()
        self.tip_window_ui = popup_window.PopupWindow(self.tip_window, self,
                                                      phonenumber)
        self.tip_window.setFixedSize(self.tip_window.width(),
                                     self.tip_window.height())
        self.tip_window.show()
        pass

    def select_identificaion_file(self):
        current_path = os.getcwd()
        filename = QFileDialog.getOpenFileName(self.groupBox_real_name,
                                               'Open file', current_path,
                                               "Excel Files (*.xlsx)")
        if filename[0] != '':
            self.identificaion_file = filename[0]
            self.qle_groupBox_real_name.setText(self.identificaion_file)
            df = pd.read_excel(self.identificaion_file)  # 读取数据文件
            df = df.astype(str)
            self.tableWidget_groupBox_real_name.setRowCount(df.shape[0])
            for row in range(df.shape[0]):
                column = 0
                for record in df.loc[row]:
                    item = QTableWidgetItem(record)
                    item.setTextAlignment(QtCore.Qt.AlignCenter)
                    self.tableWidget_groupBox_real_name.setItem(
                        row, column, item)
                    self.tableWidget_groupBox_real_name.setRowHeight(
                        column, 10)
                    column = column + 1

    def select_surveillance_order(self):
        _translate = QtCore.QCoreApplication.translate
        self.monitor_status = True
        self.lineEdit_3_normal_order.setText(_translate("Object", "监控中"))
        print("监控中", self.monitor_status)
        t = threading.Thread(target=self.monitor_order)
        t.daemon = True
        t.start()

    def batch_address_import(self):
        pass

    def monitor_order(self):
        print("monitor_order 进入", self.monitor_status)
        goods_id = self.lineEdit_normal_order.text()
        count = self.account_model.rowCount()
        for i in range(count):
            item = self.account_model.item(i, 0)
            if item.checkState() == 2:
                access_token = self.account_model.item(i, 2).text()
                addresssucc, addressdata = yemai_api.api_address_list(access_token)
                if addresssucc:
                    addr_id = addressdata['list'][0]['addr_id']
                    succ, data = yemai_api.api_good_detail(access_token, goods_id)
                    if succ:
                        sku_id = data['item']['default_sku_id']
                        succcart, data = yemai_api.api_cart_add(access_token, goods_id, sku_id)
                        if succcart:
                            succorder, dataorder = yemai_api.api_yuyue_create_order_cart(access_token, addr_id)
                            print("succorder", succorder)
                            print("dataorder", dataorder)
                            time.sleep(2)
            else:
                pass

    def user_nosm_list(self):
        account_model = QtGui.QStandardItemModel(1, 1)  # 存储任意结构数据
        account_model.setHorizontalHeaderLabels(['手机号码'])
        data = select_user_no_shiming_list()
        no_sm = []
        self.dialogsef.comboBox.clear()
        for i in data:
            no_sm.append(i[1])
        self.dialogsef.comboBox.addItems(no_sm)
        user_logins = select_user_no_shiming_list()

        for num, user in enumerate(user_logins):
            mobile = QtGui.QStandardItem(user[1])
            account_model.setItem(num, 0, mobile)
        self.dialogsef.tableView_12.setModel(account_model)

    def proxy_list(self):
        account_model = QtGui.QStandardItemModel(1, 2)  # 存储任意结构数据
        account_model.setHorizontalHeaderLabels(['订单号', 'APIKEY', '订单类型'])

        proxies = select_proxy_list()
        for num, p in enumerate(proxies):
            order = QtGui.QStandardItem(str(p[0]))
            apikey = QtGui.QStandardItem(p[2])
            otype = QtGui.QStandardItem(str(p[3]))

            account_model.setItem(num, 0, order)
            account_model.setItem(num, 1, apikey)
            account_model.setItem(num, 2, otype)
        self.dialogsef.tableView_18.setModel(account_model)

    def yuyue_success_list(self, ck_list=None):
        self.yuyue_shaixuan = False
        self.yuyue_model = QtGui.QStandardItemModel(1, 8)  # 存储任意结构数据
        self.yuyue_model.setHorizontalHeaderLabels([
            '手机号', '是否过期', '活动id', '商品id', '数量', 'addr_id', '抢购起始时间', '抢购结束时间',
            '开始监控时间', '是否成功抢购', 'id'
        ])

        proxies = select_yuyue_all()

        for num, p in enumerate(proxies):
            pay_last_time = get_timestamp(p[7])
            now = time.time()
            rid = QtGui.QStandardItem(str(p[1]))
            r1 = QtGui.QStandardItem(str(p[0]))
            if pay_last_time > now:
                guoqi = '抢购未过期'
                r1.setCheckable(True)
                r1.setCheckState(2)
            else:
                guoqi = '抢购已过期'
                r1.setCheckable(False)

            r2 = QtGui.QStandardItem(str(guoqi))
            r3 = QtGui.QStandardItem(str(p[2]))
            r4 = QtGui.QStandardItem(str(p[3]))
            r5 = QtGui.QStandardItem(str(p[4]))
            r6 = QtGui.QStandardItem(str(p[5]))
            r7 = QtGui.QStandardItem(str(p[6]))
            r8 = QtGui.QStandardItem(str(p[7]))
            r9 = QtGui.QStandardItem(str(p[9]))
            r10 = QtGui.QStandardItem(str(p[8]))

            self.yuyue_model.setItem(num, 0, r1)
            self.yuyue_model.setItem(num, 1, r2)
            self.yuyue_model.setItem(num, 2, r3)
            self.yuyue_model.setItem(num, 3, r4)
            self.yuyue_model.setItem(num, 4, r5)
            self.yuyue_model.setItem(num, 5, r6)
            self.yuyue_model.setItem(num, 6, r7)
            self.yuyue_model.setItem(num, 7, r8)
            self.yuyue_model.setItem(num, 8, r9)
            self.yuyue_model.setItem(num, 9, r10)
            self.yuyue_model.setItem(num, 10, rid)
        self.dialogsef.tableView_5.setModel(self.yuyue_model)
        self.dialogsef.tableView_5.resizeColumnsToContents()  # 自适应

    def xuanzhong_list(self):
        try:
            sjs = []
            self.dialogsef.comboBox_3.clear()
            sj = select_user_login_list()
            for i in sj:
                sjs.append(i[1])
            self.dialogsef.comboBox_3.addItems(sjs)
            count = self.account_model.rowCount()
            address = []
            for i in range(count):
                item = self.account_model.item(i, 0)
                if item.checkState() == 2:
                    token = self.account_model.item(i, 2).text()
                    shouji = self.account_model.item(i, 1).text()
                    succ, data = yemai_api.api_address_list(token)
                    self.set_log_out('获取用户地址{}:信息:{}'.format(shouji, data))
                    if succ and data.get('list'):
                        for i in data.get('list', []):
                            addr_id = i['addr_id']
                            name = i['name']
                            addr = i['mapAddr']  # i['addrdetail']
                            mobile = i['mobile']
                            address.append(
                                (shouji, addr_id, name, addr, mobile, token))
                    if succ and not data.get('list'):
                        addr_id = '还没有创建地址,速度添加地址'
                        name = '还没有创建,速度添加'
                        addr = '还没有创建,速度添加'
                        mobile = '还没有创建,速度添加'
                        address.append(
                            (shouji, addr_id, name, addr, mobile, token))

            model = QtGui.QStandardItemModel(1, 6)  # 存储任意结构数据
            model.setHorizontalHeaderLabels(
                ['手机号', '收货人', '收货地址', 'addr_id', '收货手机', 'token'])

            for num, p in enumerate(address):
                shouji = QtGui.QStandardItem(str(p[0]))
                addr_id = QtGui.QStandardItem(str(p[2]))
                addr = QtGui.QStandardItem(str(p[1]))
                name = QtGui.QStandardItem(str(p[3]))
                mobile = QtGui.QStandardItem(str(p[4]))
                token = QtGui.QStandardItem(str(p[5]))

                model.setItem(num, 0, shouji)
                model.setItem(num, 1, addr_id)
                model.setItem(num, 3, addr)
                model.setItem(num, 2, name)
                model.setItem(num, 4, mobile)
                model.setItem(num, 5, token)
            self.dialogsef.tableView_20.setModel(model)
            self.dialogsef.tableView_20.resizeColumnsToContents()  # 自适应

        except:
            pass

    def pay_list(self):
        try:
            count = self.account_model.rowCount()
            orders = []
            xuanzhong_status = False  # 有没有选中的
            for i in range(count):
                item = self.account_model.item(i, 0)
                if item.checkState() == 2:
                    xuanzhong_status = True
                    token = self.account_model.item(i, 2).text()
                    shouji = self.account_model.item(i, 1).text()
                    succ, data = yemai_api.api_order_list(token, 2, 1)
                    self.set_log_out('获取用户待付款{}:信息:{}'.format(shouji, data))
                    if succ and data.get('list'):
                        for i in data.get('list', []):
                            tid = i['tid']
                            payment = i['payment']
                            status_desc = i['status_desc']
                            title = i.get('order', [{
                                "title": '',
                                'num': ''
                            }])[0].get('title')
                            num = i.get('order', [{
                                "title": '',
                                'num': ''
                            }])[0].get('num')
                            orders.append((shouji, token, tid, payment,
                                           status_desc, title, num))
                    elif succ and not data.get('list'):
                        tid = '还没有待付款!!'
                        payment = '还没有待付款!!'
                        status_desc = '还没有待付款!!'
                        title = '还没有待付款!!'
                        num = '还没有待付款!!'
                        orders.append((shouji, token, tid, payment,
                                       status_desc, title, num))
            model = QtGui.QStandardItemModel(1, 6)  # 存储任意结构数据
            model.setHorizontalHeaderLabels(
                ['手机号', 'tid', '价格', '状态', '名称', '数量'])

            if not xuanzhong_status:
                orders = [[
                    '还没有选中账号', '还没有选中账号', '还没有选中账号', '还没有选中账号', '还没有选中账号',
                    '还没有选中账号'
                ]]
            for num, p in enumerate(orders):
                p1 = QtGui.QStandardItem(str(p[0]))
                p3 = QtGui.QStandardItem(str(p[2]))
                p4 = QtGui.QStandardItem(str(p[3]))
                p5 = QtGui.QStandardItem(str(p[4]))
                p6 = QtGui.QStandardItem(str(p[5]))
                p7 = QtGui.QStandardItem(str(p[6]))

                model.setItem(num, 0, p1)
                model.setItem(num, 1, p3)
                model.setItem(num, 2, p4)
                model.setItem(num, 3, p5)
                model.setItem(num, 4, p6)
                model.setItem(num, 5, p7)
            self.dialogsef.tableView_21.setModel(model)
        except:
            # 未选中
            model = QtGui.QStandardItemModel(1, 6)  # 存储任意结构数据
            model.setHorizontalHeaderLabels(
                ['手机号', 'tid', '价格', '状态', '名称', '数量'])
            p1 = QtGui.QStandardItem('还没有选中账号')
            p2 = QtGui.QStandardItem('还没有选中账号')
            p3 = QtGui.QStandardItem('还没有选中账号')
            p4 = QtGui.QStandardItem('还没有选中账号')
            p5 = QtGui.QStandardItem('还没有选中账号')
            p6 = QtGui.QStandardItem('还没有选中账号')

            model.setItem(0, 0, p1)
            model.setItem(0, 1, p2)
            model.setItem(0, 2, p3)
            model.setItem(0, 3, p4)
            model.setItem(0, 4, p5)
            model.setItem(0, 5, p6)
            self.dialogsef.tableView_21.setModel(model)

        def self_pick(self):
            horizontalHeader = ['账号', '状态', '订单号', '支付号']
            colunm_with_long = 180
            colunm_with_medium = 100
            self.tableWidget_self_pick.setColumnCount(len(horizontalHeader))
            self.tableWidget_self_pick.setRowCount(10)
            self.tableWidget_self_pick.setHorizontalHeaderLabels(horizontalHeader)
            self.tableWidget_self_pick.setEditTriggers(QTableWidget.NoEditTriggers)
            self.tableWidget_self_pick.setSelectionBehavior(
                QTableWidget.SelectRows)
            self.tableWidget_self_pick.setSelectionMode(
                QTableWidget.SingleSelection)
            self.tableWidget_self_pick.horizontalHeader().setSectionResizeMode(
                QHeaderView.Stretch)
            self.tableWidget_self_pick.horizontalHeader().setSectionResizeMode(
                QHeaderView.Interactive)
            self.tableWidget_self_pick.verticalHeader().setSectionResizeMode(
                QHeaderView.Stretch)
            self.tableWidget_self_pick.setColumnWidth(0, colunm_with_medium)
            self.tableWidget_self_pick.setColumnWidth(1, colunm_with_long)
            self.tableWidget_self_pick.setColumnWidth(2, colunm_with_long)
            self.tableWidget_self_pick.setColumnWidth(
                3,
                self.tableWidget.width() - colunm_with_medium -
                colunm_with_long * 2)
            self.tableWidget_self_pick.horizontalHeader().setMinimumSectionSize(40)

    def order_list(self, o_desc=None):
        count = self.account_model.rowCount()
        orders = []
        for i in range(count):
            item = self.account_model.item(i, 0)
            if item.checkState() == 2:
                token = self.account_model.item(i, 2).text()
                mobile = self.account_model.item(i, 1).text()
                succ, data = yemai_api.api_order_list(token, 1, 1)
                self.set_log_out('获取用户订单{}:信息:{}'.format(mobile, data))
                if succ and data.get('list'):
                    for i in data.get('list', []):
                        time_local = time.localtime(i['created_time'])
                        create_date = time.strftime("%Y-%m-%d %H:%M:%S", time_local)
                        goodsinfo = str(i['order'][0]['title'] + " " + i['payment'])
                        status_desc = i['status_desc']
                        try:
                            delivery = str(i['delivery']['logi_name']) + str(i['delivery']['corp_code']) + str(
                                i['delivery']['logi_no'])
                        except:
                            delivery = ""
                        orderid = i['order'][0]['oid']
                        orders.append((mobile, create_date, orderid, create_date,
                                       goodsinfo, status_desc, delivery))

                elif succ and not data.get('list'):
                    pass
        self.dialogsef.tableView_15_list_name.setRowCount(len(orders))
        for num, p in enumerate(orders):
            item = QTableWidgetItem(orders[num][0])
            item.setTextAlignment(QtCore.Qt.AlignCenter)
            self.dialogsef.tableView_15_list_name.setItem(num, 0, item)
            # ///////////////////////////////////////////////////
            item1 = QTableWidgetItem(orders[num][1])
            item1.setTextAlignment(QtCore.Qt.AlignCenter)
            self.dialogsef.tableView_15_list_name.setItem(num, 1, item1)
            self.dialogsef.tableView_15_list_name.setColumnWidth(1, 148)

            item2 = QTableWidgetItem(str(orders[num][2]))
            item2.setTextAlignment(QtCore.Qt.AlignCenter)
            self.dialogsef.tableView_15_list_name.setItem(num, 2, item2)
            self.dialogsef.tableView_15_list_name.setColumnWidth(2, 128)

            item3 = QTableWidgetItem(str(orders[num][3]))
            item3.setTextAlignment(QtCore.Qt.AlignCenter)
            self.dialogsef.tableView_15_list_name.setItem(num, 3, item3)
            self.dialogsef.tableView_15_list_name.setColumnWidth(3, 138)

            item4 = QTableWidgetItem(str(orders[num][4]))
            item4.setTextAlignment(QtCore.Qt.AlignCenter)
            self.dialogsef.tableView_15_list_name.setItem(num, 4, item4)
            self.dialogsef.tableView_15_list_name.setColumnWidth(4, 148)

            item5 = QTableWidgetItem(str(orders[num][5]))
            item5.setTextAlignment(QtCore.Qt.AlignCenter)
            self.dialogsef.tableView_15_list_name.setItem(num, 5, item5)
            self.dialogsef.tableView_15_list_name.setColumnWidth(5, 60)

            item6 = QTableWidgetItem(str(orders[num][6]))
            item6.setTextAlignment(QtCore.Qt.AlignCenter)
            self.dialogsef.tableView_15_list_name.setItem(num, 6, item6)
            self.dialogsef.tableView_15_list_name.setColumnWidth(6, 168)
